/**
* Projet Chat System
* 
* @author Yann MBOUNGOU et Jean-Christophe VENDOME
* ELEVES INGENIEUR - 4e Année - Informatique et Réseaux
* INSA TOULOUSE, Dept. GEI - 2014 - 2015
*/
package NI;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public final class TCPClient extends Thread {
    private BufferedOutputStream out;
    private BufferedInputStream in;
    private Socket client;
    private ChatNI chatni;
    private File f;
    private InetAddress addr;
    private int port;
    private FileInputStream fin;
  int bytesRead=0;
    public TCPClient(InetAddress addr,int port,ChatNI chatni,File f)
    {
            this.f=f;
            this.setChatni(chatni);
            this.port=port;
            this.addr=addr;
            System.out.println("Connexion vers "+addr.getHostAddress()+":"+port+"...");
    }
    /***********************LE*****************************/
    /***********************RUN****************************/
    @Override
    public void run()
    {
        try {
            initStreams(new Socket(addr,port));
        } catch (IOException ex) {
            System.err.println("!!IOException TCPClient = "+ex);
        }
    }
    /************************FIN RUN****************************/
    public void initStreams(Socket s)
    {
        try
        {
            client=s;            
            byte[] buf = new byte[(int)f.length()];
            in=new BufferedInputStream(new FileInputStream(f));            
            out= new BufferedOutputStream(client.getOutputStream());
            System.out.println("Sending File..."+f.getName());
            while((bytesRead= in.read(buf)) > 0)
            {
                out.write(buf, 0 , bytesRead);
            } 
            System.out.println("File transfer complete..."+f.getName());
            out.flush();
            out.close();
            in.close();
            client.close();            
        }      
        catch (UnknownHostException e) 
        {
                System.out.println("!! UnknownHostException TCPClient="+e);
        }
        catch(IOException e) 
        {
                System.out.println("!! IOException TCPClient="+e);
        }
        this.chatni.sentfile();
    }
    ///////////////////////////////////////////////

    public void setChatni(ChatNI chatni)
    {
        this.chatni = chatni;
    }     

    public Socket getClient() {
        return client;
    }
}

